package com.db.controller;

import com.db.entity.Person;
import com.db.service.PersonService;
import com.db.service.impl.PersonServiceImpl;
import com.db.util.FileUploadUitl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@WebServlet("/changePerson")
public class ChangePersonController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        try {
            HttpSession session = request.getSession();
            String username = (String) session.getAttribute("login");
            if (username == null) {
                response.sendRedirect(request.getContextPath() + "/login.jsp");
                return;
            }


            Map<String,String> map = FileUploadUitl.upload(request);
            //String name = item.getName();//如果此项表示文件，则name为文件名否则为null
            //String name =item.getFieldName();//如果此项是普通表单项。则name为表单参数的key
            //String value = item.getString();//获取表单项中的value

            Integer id =Integer.parseInt(map.get("personId"));
            String name = map.get("personName");
            String birthday = map.get("birthday");
            String sex = map.get("sex");
            String mobile = map.get("mobile");
            String address = map.get("address");
            String fileName = map.get("fileName");
            String rawFace = map.get("rawFace");
            System.out.println("file"+fileName);
            System.out.println("raw"+rawFace);

            if(fileName != null){
                String rawFilePath = request.getServletContext().getRealPath("upload_repository")+"\\"+rawFace;
                File rawFaceFile = new File(rawFilePath);
                rawFaceFile.delete();
                rawFace = fileName;
            }else{
                fileName=rawFace;
            }



            //将字符串转换为日期。或将日期转换为有格式的字符串
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date = sdf.parse(birthday);

            //将文件名.后缀名存储到face属性中，表示该用户的头像
            Person person = new Person(id,name,date,sex,mobile,address,fileName);
            PersonService ps = new PersonServiceImpl();
            ps.changePerson(person);
            response.sendRedirect(request.getContextPath() + "/showPersons");
        }catch (Exception e){
            e.printStackTrace();
        }



    }
}
